/*
 * @Author: sunkai@xinxinapp.cn
 * @Date: 2020-12-28 14:50:41
 * @LastEditTime: 2021-01-05 16:56:54
 * @LastEditors: sunkai@xinxinapp.cn
 * @Description: 
 * @FilePath: /fed-e-task-03-01/code/js/compiler.js
 */
class Compiler {
  constructor (vm) {
    this.el = vm.$el
    this.vm = vm

    this.compiler(this.el)
  }

  // 编译模板，处理文本借点和元素借点
  compiler (el) {
    const childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      // 处理文本节点
      if (this.isTextNode(node)) {
        this.compilerText(node)
      } else if (this.isElementNode(node)) {
        // 处理元素节点
        this.compilerElement(node)
      }

      // 判断node节点是否有子节点，如果有，需要递归调用compiler
      if (node.childNodes && node.childNodes.length) {
        this.compiler(node)
      }
    })
  }

  // 编译元素节点，处理指令
  compilerElement (node) {
    // console.log(node.attributes)
    // 遍历所有的属性节点
    Array.from(node.attributes).forEach(attr => {
      // 判断节点是否是指令
      let attrName = attr.name
      if (this.isDirective(attrName)) {
        // v-text => text
        attrName = attrName.substr(2)
        const key = attr.value
        this.update(node, key, attrName)
      }
    })
  }

  update (node, key, attrName) {
    const updateFn = this[attrName + 'Updater']
    updateFn && updateFn.call(this, node, this.vm[key], key)
  }

  // v-text
  textUpdater (node, value, key) {
    node.textContent = value
    new Watcher(this.vm, key, newValue => {
      node.textContent = newValue
    })
  }

  // v-model
  modelUpdater (node, value, key) {
    node.value = value
    new Watcher(this.vm, key, newValue => {
      node.value = newValue
    })

    // 双向绑定
    node.addEventListener('input', () => {
      this.vm[key] = node.value
    })
  }

  // v-html
  htmlUpdater (node, value, key) {
    node.innerHTML = value
    new Watcher(this.vm, key, newValue => {
      node.innerHTML = newValue
    })
  }

  // v-on
  onUpdater (node, value, key) {
  }

  // 编译文本节点，处理插值表达式
  compilerText (node) {
    // console.dir(node)
    // 插值表达式{{ msg }}
    const reg = /\{\{(.+?)\}\}/
    const value = node.textContent
    if (reg.test(value)) {
      // RegExp.$1 获取msg
      let key = RegExp.$1.trim()
      node.textContent = value.replace(reg, this.vm[key])

      // 创建watcher对象
      new Watcher(this.vm, key, newValue => {
        node.textContent = newValue
      })
    }
  }

  // 判断元素属性是否是指令
  isDirective (attrName) {
    return attrName.startsWith('v-')
  }

  // 判断借点是否是文本节点
  isTextNode (node) {
    return node.nodeType === 3
  }

  // 判断节点是否是元素借点
  isElementNode (node) {
    return node.nodeType === 1
  }
}